/*
 * @Author: zoujingshan 458726480@qq.com
 * @Date: 2024-03-28 10:09:45
 * @LastEditors: zoujingshan 458726480@qq.com
 * @LastEditTime: 2024-08-22 15:55:30
 * @FilePath: \宠物店-服务\src\controllers\orders.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const boom = require("boom");

const Orders = require("../models/orders");

const Pet = require("../models/pet");

exports.addOrders = async (req, reply) => {
  try {
    const pet = await Pet.findById(req.body.id);
    console.log(pet);
    if (!pet) {
      throw boom.notFound("Pet not found");
    }

    const ordersData = new Orders({
      shipDate: req.body.shipDate,
      isHealthy: true,
      completed: false,
      petId: req.body.id,

      status: pet.status,
      name: pet.name,
      photoUrls: pet.photoUrls,
      category: pet.category,
      tags: pet.tags,
    });

    const orders = new Orders(ordersData);
    return orders.save();
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.getOrders = async (req, reply) => {
  try {
    const { page = 1, pageSize = 10, status, shipDate, completed } = req.query;

    // 构造查询条件对象
    const queryConditions = {};
    if (shipDate) queryConditions.shipDate = shipDate;
    if (status) queryConditions.status = status;
    if (completed) queryConditions.completed = completed;

    const skip = (parseInt(page) - 1) * parseInt(pageSize);

    const OrdersCount = await Orders.countDocuments(queryConditions); // 计数时使用同样的查询条件

    const OrdersData = await Orders.find(queryConditions).skip(skip).limit(parseInt(pageSize));

    const responseData = {
      count: OrdersCount,
      data: OrdersData,
    };

    return responseData;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.getOrdersDetail = async (req, reply) => {
  try {
    const id = req.params.orderId;
    const order = await Orders.findById(id);
    return order;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.deleteOrders = async (req, reply) => {
  try {
    const id = req.params.id;
    const pet = await Orders.findByIdAndDelete(id);
    return pet;
  } catch (err) {
    throw boom.boomify(err);
  }
};

exports.getOrdersbyPetId = async (req, reply) => {
  try {
    const id = req.params.petId;
    const orders = await Orders.find({ petId: id });
    return orders;
  } catch (err) {
    throw boom.boomify(err);
  }
};
